<?php

if(!defined("ROOT")) define("ROOT", $_SERVER['DOCUMENT_ROOT']);

class Gallery
{
   var $DB_obj  = null;
   var $meccano = null;
   var $params  = array();
   var $error   = false;


   function Gallery($DB = null, $MECCANO = null)
   {
      if(is_object($DB))
      {
         $this->DB_obj = &$DB;
      } else
      {
         $this->error['system'][] = "No DateBase Object registered!";
      }

      if(is_object($MECCANO))
      {
         $this->meccano = &$MECCANO;
      } else
      {
         $this->error['system'][] = "No MECCANO Object registered!";
      }

      $this->SetParams();
   }

   function Get($category = '', $mode = '')
   {
      $modes     = array('a','t','d','c','r','p');
      // OUTPUT ORDERS: a - as intput, t - by title, d - by date, c - by category, r - random, p - popularity
      $sort  = ' ASC';
      $order = '';

      if(strlen($mode) > 1)
      {
         if(substr($mode, 1, 1) == '-') $sort = ' DESC';
      }
      $mode = substr($mode, 0, 1);
      $mode = in_array($mode, $modes) ? $mode : 'a';

      switch ($mode)
      {
         case 'p':
            // Order by Popularity
            $order = " ORDER BY ph.viewed" . $sort;
            break;

         case 't':
            // Order by Title
            $order = " ORDER BY BINARY ph.title" . $sort;
            break;

         case 'd':
            // Order by Date
            $order = " ORDER BY ph.dat" . $sort;
            break;

         case 'c':
            // Order by Category
            if(count($list) > 1 || $list === false)
            {
               $order = ' GROUP BY ph.cat' . $sort;
            }
            break;

         case 'r':
            // Random order
            $order = " ORDER BY RAND()";
            break;

         case 'a':
            // Order as inputed
         default:
            $order = " ORDER BY ph.id" . $sort;
      }

      isDigit($category);
      if($category == false) $category = $this->meccano->GetIdForNode('gallery');
      $categories = $this->meccano->ListOfID($category);
      if($categories == false) return false;

      $categories = implode(',',$categories);

      $this->DB_obj->sql = "SELECT ph.*, trs.title AS category FROM meccano_gallery AS ph LEFT JOIN meccano_tree AS tr ON ph.cat = tr.id LEFT JOIN meccano_treetranslates AS trs ON tr.id = trs.id WHERE ph.cat IN (" . $categories . ") AND trs.lang = '" . $this->params['language'] . "'" . $order;

      $vars = $this->DB_obj->DB_Fetch();

      for ($i=0, $t=$this->DB_obj->rows; $i<$t; $i++)
      {
         $title = @unserialize($vars[$i]['title']);
         $description = @unserialize($vars[$i]['description']);

         $vars[$i]['title']       = $title[$this->params['language']];
         $vars[$i]['description'] = $description[$this->params['language']];
      }

      return $vars;
   }


   function Lost()
   {
      $this->DB_obj->sql = "SELECT * FROM `meccano_gallery` WHERE `cat` NOT IN (SELECT `id` FROM `meccano_tree`);";
      return $this->DB_obj->DB_Fetch();
   }


   function View($id, $count = false)
   {
      isDigit($id);
      if($id == false) return false;
      settype($count, 'bool');

      if($count === true)
      {
         $this->DB_obj->sql = "UPDATE meccano_gallery SET viewed = viewed + 1 WHERE id = " . $id;
         $this->DB_obj->DB_Query();
      }

      $this->DB_obj->sql = "SELECT gal.*, tr.title AS category FROM meccano_gallery AS gal LEFT JOIN meccano_tree AS tree ON tree.id = gal.cat LEFT JOIN meccano_treetranslates AS tr ON tree.id = tr.id WHERE tr.lang = '".$this->params['language']."' AND tree.module = 'gallery' AND gal.id = ". $id;
      $photo = $this->DB_obj->DB_Fetch();

      if(isset($photo[0]['id']))
      {
         $this->DB_obj->sql = "SELECT id FROM meccano_gallery WHERE cat = " . $photo[0]['cat'] . " ORDER BY dat";
         $this->DB_obj->DB_Fetch();

         foreach ($this->DB_obj->fetched as $value)
         {
            $curent_gallery[] = $value['id'];
         }
         $photo[0]['gallery'] = &$curent_gallery;
         $photo[0]['prev']    = false;
         $photo[0]['next']    = false;

         $title = @unserialize($photo[0]['title']);
         $description = @unserialize($photo[0]['description']);
         $photo[0]['title'] = $title[$this->params['language']];
         $photo[0]['description'] = $description[$this->params['language']];

         $point = array_search($id, $curent_gallery);
         if(($count = count($curent_gallery)) > 1)
         {
            if($point === $count-1)
            {
               $photo[0]['next'] = $curent_gallery[0];
            } else
            {
               $photo[0]['next'] = $curent_gallery[$point+1];
            }
            if($point === 0)
            {
               $photo[0]['prev'] = $curent_gallery[$count-1];
            } else
            {
               $photo[0]['prev'] = $curent_gallery[$point-1];
            }
         }

         return $photo;
      }

      return false;
   }

   function JustPhoto($id)
   {
      isDigit($id);
      if($id == false) return false;
      $this->DB_obj->sql = "SELECT * FROM meccano_gallery WHERE id = ".$id;

      $vars = $this->DB_obj->DB_Fetch();
      $vars[0]['title'] = @unserialize($vars[0]['title']);
      $vars[0]['description'] = @unserialize($vars[0]['description']);

      return $vars;
   }

   function Count($category = false, $mode = false)
   {
      $module = 'gallery';
      $categories = null;
      $result = array();

      isDigit($category);
      $this->meccano->SetParams('root=hide');
      $tree = $this->meccano->GetFlatList($category, $module);
      $this->meccano->SetParams();

      if(count($tree) >= 1)
      {
         foreach ($tree as $value)
         {
            $categories[] = $value['id'];
         }

         $categories = implode(',', $categories);

         $this->DB_obj->sql = "SELECT t1.cat, COUNT(*) AS counts, (SELECT t2.file FROM meccano_gallery AS t2 WHERE t2.cat = t1.cat ORDER BY RAND() LIMIT 1) AS file FROM meccano_gallery AS t1 WHERE t1.cat IN (".$categories.") GROUP BY t1.cat";
         $counts = $this->DB_obj->DB_Fetch();

         for($i=0, $t=count($tree); $i<$t; $i++)
         {
            $newtree[$tree[$i]['id']] = $tree[$i];
         }
         unset($tree);

         for($i=0, $t=$this->DB_obj->rows; $i<$t; $i++)
         {
            $counts[$i] += $newtree[$counts[$i]['cat']];
            unset($counts[$i]['lock']);
            unset($counts[$i]['module']);
            unset($counts[$i]['folder']);
         }
         unset($newtree);


         return $counts;
      }

      return false;
   }


   function Delete($id)
   {
      $del = array();
      if(is_array($id))
      {
         $del = array_filter($id, 'isDigit');
      } else
      {
         isDigit($id);
         if($id !== false) $del[] = $id;
      }
      unset($id);

      if(count($del) > 0)
      {
         $del = implode(',', $del);
         $this->DB_obj->sql = "SELECT file FROM meccano_gallery WHERE id IN (".$del.");";
         $files = $this->DB_obj->DB_GetFlat();

         if($files != false) foreach ($files AS $value)
         {
            @unlink(ROOT.$this->meccano->system['gallery_photos'].'/'.$value);
            @unlink(ROOT.$this->meccano->system['gallery_preview'].'/'.$value);
         }

         $this->DB_obj->sql = "DELETE FROM meccano_gallery WHERE id IN (".$del.");";

         return $this->DB_obj->DB_Query();
      }

      return false;
   }

   function SetParams($params = 'clear')
   {
      if($params == 'clear')
      {
         $this->params['language']      = $this->meccano->system['lang'][0];
         return true;
      }

      $params = explode(';', $params);

      foreach ($params as $value)
      {
         $p = explode('=', $value);
         switch ($p[0])
         {
            case 'language':
               strtolower($p[1]);
               if(in_array($p[1], $this->meccano->system['lang'])) $this->params['language'] = $p[1];
               break;
         }
      }

      return true;
   }
}
?>